<?php
require_once sfConfig::get('dm_core_dir').'/plugins/dmUserPlugin/modules/dmUser/lib/BasedmUserActions.class.php';
require_once sfConfig::get('sf_root_dir').'/apps/front/modules/score/actions/components.class.php';
require_once sfConfig::get('sf_root_dir').'/lib/vendor/diem/symfony/lib/plugins/sfDoctrinePlugin/test/functional/fixtures/lib/model/doctrine/UserTable.class.php';


class dmUserActions extends BasedmUserActions  
{  
  //redirect after sigin
  protected function redirectSignedInUser(dmWebRequest $request)  
  {  
    $redirectUrl = $this->getUser()->getReferer($request->getReferer());  
 
    $this->redirect('' != $redirectUrl ? $redirectUrl : '@signin');  
  }  
 /**  
   * Handle dmUser/form form validation and creates the user account, then authenticates the user  
   */  
	//LINHNH
	//get score and id which have send with AJAX. 
	//Save them to database
					/*
				 * Save to database
				 * and check if this score is new high score 
				 * Save Error : echo 0 
				 * Not Sign in : 1 
				 * Save ok but not HS : echo 2 
				 * Save ok and is HS : echo 3 
				 */ 
	public function executeGetinformation(dmWebRequest $request)
	{
		$returnValue = "0"; 
		//disable HTTP header 
		$this->response->setHeaderSitiuation(false);
		//disable layout 
		$this->setLayout(false); 
		//Check sending method and get data
		if ($request->isMethod('post')) {
			$scoreUser = $_POST["score"];
			$arrInfo = explode("gameId=", $scoreUser);		
			$scoreUser = $arrInfo[0]; 
			$gameId = $arrInfo[1];  	
			//echo $score;			
			//get current userName; 
			$userComponent = $this->getUser();
			if ($userComponent->isAuthenticated() ){
				$userId = $userComponent->getUserId(); 
				//echo $userComponent->getUsername();
	
				//echo $gameId.$userId.$scoreUser; 
				$returnValue = "2" ;
				// Check if is new High Score 
				$rankingRow = new Score(); 
				$ranking = ScoreTable::getInstance(); 
				if ( $ranking->count() < 5  ){ 
						$returnValue = "3"; 
				}
				else {
					$rankingArray = $ranking->createQuery('m')->addOrderBy('m.value DESC')->execute();
					foreach ($rankingArray as $i => $record){
						if ($i < 5 ){ 
							if ($scoreUser > $record->value) { 
								$returnValue = "3"; 
								break; 
							}
							else { 
								//echo "  ".$i.": ".$record->value.$record->game.$record->user."---";
							} 
						} 
						else { 
							break; 
						}
					}			
				}
				
				//Save Score 
				$scoreNew = new Score(); 
				$scoreNew->set("game", 1); 
				$scoreNew->set("user", $userId); 
				$scoreNew->set("value", $scoreUser); 
				$scoreNew->save(); 
		
			}
			else {
				// exception 
				$returnValue = "1"; 
			}
		}
		else {
			//exception
			$returnValue = "0"; 
		}
		echo $returnValue ; 
	} 
	
	//LINHNH
	//get ranking for game that have Id is id 
	/*
	 * Return value 
	 * 0-ERROR : DATABASE ERROR 
	 * XML text -> OK 
	 */
	
	public function executeGetranking(dmWebRequest $request)
	{
		$returnValue = "0-ERROR"; 
		//disable HTTP header 
		$this->response->setHeaderSitiuation(false);
		//disable layout 
		$this->setLayout(false); 
		//Check sending method and get data
		{
			$rankingRow = new Score(); 
			$ranking = ScoreTable::getInstance(); 
			if (!$ranking) { 
				return "0-ERROR"; 
			}
			$userTable = Doctrine_Core::getTable('dmUser'); 
			//$queryString = "username = '".$nameUser."'"; 
			//$userSelection = $userTable->createQuery('m')->where($queryString)->execute();
			$rankingArray = $ranking->createQuery('m')->addOrderBy('m.value DESC')->execute();
			for ($i = 0; $i < 5; $i++) {
				if ( $i < $rankingArray->count() ){ 
					$queryString = "id = '".$rankingArray[$i]->user."'"; 
					$userSelection = $userTable->createQuery('m')->where($queryString)->execute(); 
					$a[$i][0] = $userSelection[0]->username;  
					$a[$i][1] = $rankingArray[$i]->value;
					$yearOnly = explode(" ", $rankingArray[$i]->updated_at);	
					$a[$i][2] = $yearOnly[0]; 				 
				} 
				else {
					$a[$i][0] = "--"; 
					$a[$i][1] = "--"; 	
					$a[$i][2] = "--";
				}
				//echo "  ".$i.": ".$a[$i][0].$a[$i][1].$a[$i][2]."---";	
			}
			$returnValue = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<list>
  <user1>
  	<name> ".$a[0][0]." </name>
  	<score> ".$a[0][1]." </score>
  	<time> ".$a[0][2]." </time>
  </user1>
  <user2>
  	<name> ".$a[1][0]." </name>
  	<score> ".$a[1][1]." </score>
  	<time> ".$a[1][2]." </time>
  </user2>
  <user3>
  	<name> ".$a[2][0]." </name>
  	<score> ".$a[2][1]." </score>
  	<time> ".$a[2][2]." </time>
  </user3>
  <user4> 
  	<name> ".$a[3][0]." </name>
  	<score> ".$a[3][1]." </score>
  	<time> ".$a[3][2]." </time>
  </user4>
  <user5>
  	<name> ".$a[4][0]." </name>
  	<score> ".$a[4][1]." </score>
  	<time> ".$a[4][2]." </time>
  </user5>
</list>"; 

		}
		echo $returnValue ; 
	} 

	//LINHNH
	/*
	 * execute login information
	 * Return value 
     * 0-POST ERROR
     * 2-DATABASE ERROR
     * 2-NO USER FOUND
     * 3 : COMPLATE 
     * 4 : USERNAME OK BUT PASS IS WRONG
	 */  
	
	public function executeLoginfromgame(dmWebRequest $request)
	{
		$returnValue = "0-POST ERROR"; 
		//disable HTTP header 
		$this->response->setHeaderSitiuation(false);
		//disable layout 
		$this->setLayout(false); 
		//Check sending method and get data
		if ($request->isMethod('post')) {
			$nameUser = $_POST["name"];
			$arrInfo = explode("pass=", $nameUser);		
			$nameUser = $arrInfo[0]; 
			$passUser = $arrInfo[1]; 
			// Check if is new High Score 
			$userTable = Doctrine_Core::getTable('dmUser'); 
			$queryString = "username = '".$nameUser."'"; 
			$userSelection = $userTable->createQuery('m')->where($queryString)->execute();
			if (!$userSelection){
				$returnValue = "2-DATABASE ERROR"; 
			}
			else { 
				if ($userSelection->count()){ 
					
					$saltString = $userSelection[0]->salt;
					$algorithm = sfConfig::get('dm_security_algorithm_callable', 'sha1');
					$newPass =  call_user_func_array($algorithm, array($saltString.$passUser));
					
					if ( strcmp($userSelection[0]->password,$newPass)  == 0 ) 
					{
						//Success
						$returnValue = "3"; 
						
						
						/************* / 
						 * 
						 */
					} 
					else {
						$returnValue = "4"; 
					} 
				}else { 
					$returnValue = "2-NO USER FOUND";
				}
			} 	
		}
		else {
			//exception
			$returnValue = "0-POST ERROR"; 
		}
		echo $returnValue ; 
	} 
	
	//LINHNH
	//check login status 
	/*
	 *Return Value 
	 * 3: LOGIN  NOW 
	 * 0: NOT LOGIN  
	 */  
	public function executeChecklogin(dmWebRequest $request)
	{
		$returnValue = "0"; 
		//disable HTTP header 
		$this->response->setHeaderSitiuation(false);
		//disable layout 
		$this->setLayout(false); 
		//Check sending method and get data
		//echo $score;			
		//get current userName; 
		$userComponent = $this->getUser();
		if ($userComponent->isAuthenticated()){
			$returnValue = "3"; 
		}
		else {
			// exception 
			$returnValue = "0"; 
		}
	echo $returnValue ; 
	} 
} 